package com.whj.servicepassengeruser.servie.impl;

import com.whj.internalcommon.constant.CommonStatusEnum;
import com.whj.internalcommon.dto.PassengerUser;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.servicepassengeruser.mapper.PassengerUserMapper;
import com.whj.servicepassengeruser.servie.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * @Auther: wanghaijun
 * @Date: 2022/12/28 - 12 - 28 - 14:07 
 * @Description: com.whj.servicepassengeruser.servie.impl
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private PassengerUserMapper passengerUserMapper;

    /**
     * 根据手机号登录 注册 用户信息
     *
     * @param passengerPhone
     * @return
     */
    @Override
    public ResponseResult loginOrRegister(String passengerPhone) {

        //根据手机号查询用户信息
        HashMap<String, Object> map = new HashMap<>();
        map.put("passenger_phone", passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);

        //判断用户信心是否存在
        if (passengerUsers.size() == 0) {

            //如果不存在，插入用户信息
            PassengerUser passengerUser = new PassengerUser();
            //随机给新用户赋值名字
            passengerUser.setPassengerName("张三");
            passengerUser.setPassengerPhone(passengerPhone);
            passengerUser.setPassengerGender((byte) 0);
            passengerUser.setState((byte) 0);
            LocalDateTime now = LocalDateTime.now();
            passengerUser.setCreateTime(now);
            passengerUser.setUpdateTime(now);

            passengerUserMapper.insert(passengerUser);
        }

        return ResponseResult.success();
    }

    /**
     * 通过手机号查询用户的信息
     *
     * @param passengerPhone
     * @return
     */
    @Override
    public ResponseResult getUserByPhone(String passengerPhone) {

        //根据手机号查询用户信息
        HashMap<String, Object> map = new HashMap<>();
        map.put("passenger_phone", passengerPhone);
        List<PassengerUser> passengerUsers = passengerUserMapper.selectByMap(map);

        if (passengerUsers.size() == 0) {
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXISTS.getCode(), CommonStatusEnum.USER_NOT_EXISTS.getValue());
        } else {
            PassengerUser passengerUser = passengerUsers.get(0);
            return ResponseResult.success(passengerUser);
        }

    }
}
